<?php
/**
 * Created by PhpStorm.
 * User: zhaoye
 * Date: 2016/12/26
 * Time: 上午9:37
 */


namespace ZPHP\Client;

use ZPHP\Core\Config;
use ZPHP\Core\Container;
use ZPHP\Core\Factory;
use ZPHP\Core\Log;
use ZPHP\Core\WSRequest;
use ZPHP\Socket\Callback\SwooleWebSocket as ZSwooleWebSocket;

class SwooleWebSocket extends ZSwooleWebSocket
{

    /**
     * @var WSRequest $websocketRequest;
     */
    private $websocketRequest;
    private $buff = [];

    public function onMessage($server, $frame)
    {
        try {
            if (empty($frame->finish)) { //数据未完
                if (empty($this->buff[$frame->fd])) {
                    $this->buff[$frame->fd] = $frame->data;
                } else {
                    $this->buff[$frame->fd] .= $frame->data;
                }
            } else {
                if (!empty($this->buff[$frame->fd])) {
                    $frame->data = $this->buff[$frame->fd] . $frame->data;
                    unset($this->buff[$frame->fd]);
                }
            }
            $websocketRequest = clone $this->websocketRequest;
            $websocketRequest->init($server, $frame);
            $httpResult = $this->dispatcher->distribute($websocketRequest);
            if($httpResult!=='NULL') {
                if(!is_string($httpResult)){
                    if(strval(Config::getField('project','type'))=='api'){
                        $httpResult = json_encode($httpResult);
                    }else{
                        $httpResult = strval($httpResult);
                    }
                }
                $server->push($frame->fd, $httpResult);
            }
        } catch (\Exception $e) {
            $msg = DEBUG===true?$e->getMessage():"系统异常了!";
            $server->push($frame->fd, $msg);
        }
    }

    public function onWorkerStart($server, $workerId)
    {
        parent::onWorkerStart($server, $workerId); // TODO: Change the autogenerated stub
        if (!$server->taskworker) {
            $this->websocketRequest = Container::Core('WSRequest', $this->coroutineTask);
//            $this->websocketRequest = Factory::getInstance(\ZPHP\Core\WSRequest::class, $this->coroutineTask);
        }
    }

    public function onClose(){
//        $args_array = func_get_args();
//        $swoole_server = $args_array[0];
//        $fd = $args_array[1];
//        $from_id = $args_array[2];
    }

}
